package com.zhang;

import com.zhang.common.codec.MyDecoder;
import com.zhang.common.codec.MyEncoder;
import com.zhang.common.config.GlobalConfig;
import com.zhang.handler.HeartDataHandler;
import com.zhang.handler.ServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * tcp服务端  非启动类
 */
public class TCPServer {

    /**
     * tcp服务端跟客户端通信 端口
     */
    private int port;
    /**
     * 日志对象
     */
    static private Logger log = LoggerFactory.getLogger(TCPServer.class);
    /**
     * accept 线程组
     */
    private EventLoopGroup bossGroup = new NioEventLoopGroup();
    /**
     * work 线程组
     */
    private EventLoopGroup workGroup = new NioEventLoopGroup();
    /**
     * 服务启动器
     */
    private ServerBootstrap b = new ServerBootstrap();

    public TCPServer() {
        this.port = GlobalConfig.props.getInt("transPort");
    }

    public void start(){
        b.group(bossGroup,workGroup);
        b.channel(NioServerSocketChannel.class);
        b.option(ChannelOption.SO_BACKLOG,1024);
        b.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new IdleStateHandler(60,80,120));
                ch.pipeline().addLast("myDecoder",new MyDecoder(Integer.MAX_VALUE,0,4,0,4));
                ch.pipeline().addLast("myEncoder",new MyEncoder());
                ch.pipeline().addLast(new HeartDataHandler());
                ch.pipeline().addLast("serverHandler",new ServerHandler());
            }
        });
        try{
            //同步绑定端口
            ChannelFuture future = b.bind(port).sync();
            if(future.isSuccess()){
                log.info("服务端启动成功 端口是 {}",port);
            }

            future.channel().closeFuture().sync().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    log.info("等待tcp服务退出...");
                    bossGroup.shutdownGracefully();
                    workGroup.shutdownGracefully();
                }
            });
        }catch (Exception e){
            log.error("绑定端口失败 端口为={}",port);
        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
            log.info("等待tcp服务退出...");
            System.exit(0);
        }



    }
}
